package com.fgl;

import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description
 * @Author fuguangli businessfgl@163.com
 * @Create date:    2017/9/14
 */
public class Test {
    public static void main(String[] args) throws IOException {


        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring-data-mongo.xml");

        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");


        MongoTemplate template = (MongoTemplate) mongoOperation;
        DB db = template.getDb();
        GridFS fs = new GridFS(db, "file");
//        File file = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\sql_t.jpg");
//        GridFSInputFile inputFile = fs.createFile(file);
//        inputFile.put("contentType",file.getName().substring(file.getName().indexOf(".")+1));
//        inputFile.save();


        GridFSDBFile gridFSFile = fs.findOne("sql_t.jpg");
        InputStream inputStream = gridFSFile.getInputStream();

        File outDir = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\out");
        if (!outDir.exists()) {
            outDir.mkdirs();
        }
        File outFile = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\out\\out.jpg");
        if (!outFile.exists()) {
            outFile.createNewFile();
        }

        gridFSFile.writeTo(outFile);


        Query query = new Query(Criteria.where("").orOperator(

        ));
        mongoOperation.findOne(new Query(Criteria.where(
                "id").is("100")), Employee.class, "employees");
    }
}
